//
//  OMOrderListViewController.m
//  OMENGO_NEW
//
//  Created by 梁尚嘉 on 2017/5/2.
//  Copyright © 2017年 Kamfat. All rights reserved.
//

#import "OMOrderListViewController.h"
//
//      订单状态
//
/** 未完成*/
NSString *const OMOrderStatusUnfinished = @"unfinished";
/** 已完成*/
NSString *const OMOrderStatusCompleted = @"completed";
/** 已取消*/
NSString *const OMOrderStatusCanceled = @"allCanceled";
//=============================================
#import "OMOrderTableCell.h"
#import "OMOrderButtonActionHelper.h"
@interface OMOrderListViewController ()
@property (nonatomic, assign) NSUInteger pageNumber;
@property (nonatomic, assign) NSUInteger pageSize;
@end

@implementation OMOrderListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupUI];
    [self startAnimating:YES];

    @weakify(self);
    [SMNotificationMonitorRACSignal(OM_NOTIFICATION_KEY_LOGIN_SUCCESS) subscribeNext:^(id x) {
        @strongify(self);
        [self startAnimating:YES];
        self.pageNumber = 1;
        self.pageSize = self.orders.count;
        [self getOrderList];
    }];

    [SMNotificationMonitorRACSignal(OMORDER_NEED_REFRESH_NOTIFICATION) subscribeNext:^(id x) {
        @strongify(self);
        [self startAnimating:YES];
        self.pageNumber = 1;
        self.pageSize = self.orders.count;
        [self getOrderList];
    }];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if ([Storage isLogin]) {
        [self reloadDataFromNetWork];
    }else {
        [self startAnimating:NO];
    }
}

- (void)setupUI
{

    @weakify(self);
    [self.tableView.kt_header addRefreshWithBlock:^{
        @strongify(self);
        self.pageNumber = 0;
        [self getOrderList];
    }];

    //分页
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        @strongify(self);
        self.pageNumber++;
        [self getOrderList];
    }];
    footer.stateLabel.font = SM_CFont(24);
    footer.stateLabel.textColor = SM_darkGrayColor;
    footer.triggerAutomaticallyRefreshPercent = SM_SIZE(-30);
    footer.automaticallyHidden = true;
    [footer setTitle:@"没有更多订单了的" forState:MJRefreshStateNoMoreData];
    self.tableView.mj_footer = footer;


    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.tableView.sectionHeaderHeight = DBL_EPSILON;
    self.tableView.sectionFooterHeight = SM_SIZE(20);
    self.emptyImage = [UIImage imageNamed:@"dindan"];
    self.emptyDataMessage = @"没找到相关订单";
    self.navigationBarHidden = true;
}

- (void)reloadDataFromNetWork
{
    self.pageNumber = 1;
    self.pageSize = self.orders.count;
    [self getOrderList];
}

#pragma mark - Network
- (void)getOrderList
{
    [self.task cancel];
    self.task =[KTHttpUtils
                 GET_NOCACHE:@"member/order/list.jhtml"
                  parameters:@{@"status":self.orderStatus,
                               @"pageNumber":@(self.pageNumber),
                               @"pageSize":@(self.pageSize)}
                    progress:nil
                  completion:^(id responseObject, BOOL isSuccess, NSString *message) {

                      if (isSuccess) {

                          OMOrderResponse *response = [OMOrderResponse mj_objectWithKeyValues:responseObject[OMDatumKey]];
                          for (OMOrder *order in response.list) {
                              for (OMOrderItem *orderItem in order.orderItems) {
                                  orderItem.image = [responseObject[OMImagePrefix] stringByAppendingString:orderItem.image?:@""];
                              }
                          }

                          //UI reload
                          if (self.tableView.mj_footer.isRefreshing) {

                              [self.orders addObjectsFromArray:response.list?:@[]];
                          }else {

                              self.orders = [response.list mutableCopy];
                          }

                          [self.tableView reloadData];
                          self.pageNumber == response.totalPage?[self.tableView.mj_footer endRefreshingWithNoMoreData]:[self.tableView.mj_footer endRefreshing];
                      }else {
                          if (self.tableView.mj_footer.isRefreshing) {
                              [self.tableView.mj_footer endRefreshing];
                              self.pageNumber --;
                          }
                      }
                    [self startAnimating:NO];
                    [self.tableView.kt_header endRefreshWithType:isSuccess?KTHeaderEndRefreshSuccessType:KTHeaderEndRefreshErrorType];
    }];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.orders.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NaviPush(@"OMOrderDetailTabsViewController", @{@"orderSn":self.orders[indexPath.section].sn});
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    OMOrderTableCell *cell = [OMOrderTableCell tableViewCellWithTableView:tableView];
    [cell configureCellWithObj:self.orders[indexPath.section]];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [OMOrderTableCell cellHeightWithOrder:self.orders[indexPath.section]];
}


- (NSUInteger)pageSize
{
    if (_pageSize < 20) {
        _pageSize = 20;
    }
    return _pageSize;
}

- (NSUInteger)pageNumber
{
    if (!_pageNumber) {
        _pageNumber = 1;
    }
    return _pageNumber;
}

@end
